/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Bridging;

import Codec.MessageCodecFactory;
import Message.*;
import PIServer.LocalSettings;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.mina.core.RuntimeIoException;
import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

/**
 *
 * @author Nhan Nguyen
 */
public class BridgeService {
    private final static long CONNECT_TIMEOUT = 5*1000; // 5 seconds

    public static ConcurrentHashMap<Integer, IoSession> connectionList =
            new ConcurrentHashMap(new HashMap<Integer, IoSession>());

    public static void processCommand(IoSession session, int userID, String userName, Message clientMsg) throws InterruptedException {

        if (userID <= 0) return;
        IoSession clientSession = connectionList.get(userID);

        if ((clientSession == null)||(!clientSession.isConnected())) {

            if (clientSession!=null) {
                connectionList.remove(userID);
            }

            final NioSocketConnector connector = new NioSocketConnector();

            // Configure the service.
            connector.setConnectTimeoutMillis(CONNECT_TIMEOUT);
            DefaultIoFilterChainBuilder chain = connector.getFilterChain();
            chain.addLast("decoder", new ProtocolCodecFilter(MessageCodecFactory.getInstance()));
            connector.setHandler(new BridgeSessionHandler(userID));

            try {
                ConnectFuture future = connector.connect(
                        new InetSocketAddress(LocalSettings.CARDGAME_HOST, LocalSettings.CARDGAME_PORT));
                future.awaitUninterruptibly();
                clientSession = future.getSession();
                clientSession.setAttribute("userid",userID);
                connectionList.put(userID, clientSession);

                Message msg = new Message(BeanConstant.SYS_SILENT_LOGIN_REQUEST, ServiceConstant.CHAT_SERVICE);
                // user name
                SerializerHelper.writeString(Base64.toBase64(userName), msg);
                clientSession.write(msg);

            } catch (RuntimeIoException e) {
                System.err.println("Failed to connect.");
                e.printStackTrace();
            }
//            session.getCloseFuture().awaitUninterruptibly();
//            connector.dispose();
        }

        if (clientSession.isConnected()) {
            clientSession.write(clientMsg);
        }
    }
}
